/*******************************************************
  > Copyright (C) 2024 ==IOT== All rights reserved.
  > File Name: 创建一个子进程.c
  > Author: lv1
  > Website:www.lv1.org
  > Created Time: 2024年08月03日 星期六 11时24分17秒
 ***************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>//文件属性的操作
#include <sys/types.h>//数据类型定义
#include <unistd.h>//linux下的系统调用，进程操作
#include <fcntl.h> //文件控制,open等
int main(int argc, const char* argv[])
{
	FILE* fp = NULL;
	DIR* dir;
	struct dirent* dent;
	char srcpath[100]={0};
	dir = opendir("../test/");
	if (dir == NULL) {
		printf("open dir error\n");
		exit(-1);
	}
	dent = readdir(dir);

	char old_name[100]={0};
	char temp1[100]={0};//读取用的
	char temp2[100]={0};//存放用的
	char destpath[100]={0};
	int res = 0;
	int i = 1 ;//新名字用的
	FILE *newfp = NULL;
	// 读取目录里面的所有文件！！！
	while (dent != NULL) {

		if (dent->d_name[0] == '.') {
			dent = readdir(dir);
			continue;
		}

		// 打开文件
		strcpy(old_name,dent->d_name);
		sprintf(srcpath,"../test/%s",old_name);
		fp = fopen(srcpath, "r");		//这样打开文件才对！！！
		if (fp == NULL) {
			printf("open file error\n");
			closedir(dir);
			exit(-1);
		}

		//打开新文件
		sprintf(destpath,"../test/new_%d.txt",i);
		i++;
		newfp = fopen(destpath,"w");
		if (newfp == NULL) {
			printf("open new_file error\n");
			closedir(dir);
			exit(-1);
		}
		

		// 读取文件内容并打印
		while (1) {
			res = fread(temp1,sizeof(temp1),1,fp);
			if(res>=0){
				temp1[strlen(temp1)]='\0';
				printf("%s\n", temp1);
				rewind(fp);
				fwrite(fp,sizeof(temp1),1,newfp);
				break;
			}
			if(res<0){
				perror("fread");			//这是字符串!!!
				break;
			}
		}

		fclose(fp);

		dent = readdir(dir);
	}
	closedir(dir);





	//进程
	pid_t pid;
	pid = getpid();
	pid = fork();
	if(pid == 0){
		printf("这是子1进程：%d\n",getpid());		
		exit(0);
	}
	else if(pid>0){
		printf("这是父进程:%d\n",getpid());
	}

	return 0;

}
